﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Text;
using TestNetty.Infrastructure.Common.DTO;

namespace TestNetty.Service.Handlers
{
    /// <summary>
    /// Encoder Packet
    /// </summary>
    public class EncoderHandler : MessageToByteEncoder<PacketResponse<string>>
    {
        /// <summary>
        /// Encode每调用一次,就实例化一个数据包出去
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <param name="output"></param>
        protected override void Encode(IChannelHandlerContext context, PacketResponse<string> message, IByteBuffer output)
        {
            // 这里的output就是一个数据容器了,容器里可以装很多的字节
            message.Body = "hello world.";
            // 响应消息体序列化
            byte[] bodyArray = message.Serialize();
            output.WriteInt(message.Checkbit);//0-3 校验位(4B)
            output.WriteInt(message.Length);//4-7 整包长度(4B)
            output.WriteInt(message.CommandId);//8-11 指令编号(4B) 
            // 写入响应消息体(写字节数组)
            output.WriteBytes(bodyArray);
        }
    }
}
